import pyaudio, sys, string, serial, time

# serial setting 
#ser = serial.Serial(1, 9600, timeout=0, parity='N', stopbits=1, xonxoff=0, rtscts=0)
ser = serial.Serial()
ser.baudrate = 9600
ser.port = 0
ser.open()
ser.stopbits = 1

ser.write("s")
time.sleep(0.01)
ok = ser.readline() 
print "Initial pressure is ", ok
prs = 0
for h in ok.split(','):
    prs = prs + int(h)

# sound setting ###########
chunk = 128
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 22050
RECORD_SECONDS =60

p = pyaudio.PyAudio()
stream = p.open(format = FORMAT,
                channels = CHANNELS, 
                rate = RATE, 
                input = True,
                output = True)


# Signal setting ###########
init_st = 30
init_fi =200
init_zero = 300
zero_term = 100

c = 0
avg = 0
avgZero = 0.0
zeroFlag = True;
zero= 0.0
preZero = 0.0
zeroCnt=0
state = False
vibState = False
vibLoop = 0
vibLoopState = False

print "* recording"
while 1:
    
    #################
    # pre processing
    #################
    data = stream.read(chunk)
    ii = False
    val = 0
    for d in data:
        # neglect low
        if ii is True:
            ii = False
            val = ord(d) + val
        else:
            ii = True
    
    ####################
    # Signal Processing 
    ####################
    if c < 99999999:
        c = c + 1
    
    
    #
    # initialization
    if c > init_st and c < init_fi :
       avg = avg + val
       continue
    elif (c == init_fi):
        avg = avg/(init_fi - init_st)
        print "Average noise is "+str(avg)
        continue
    
    # Avg zero crossing rate check
    # state of avg over is true, less is false
    if c > init_fi and c < init_zero:
        if avg < val and zeroFlag is False:
            avgZero = avgZero + 1
            zeroFlag = True
        elif avg > val and zeroFlag is True:
            avgZero =avgZero + 1
            zeroFlag = False
        else:
            continue
    elif c == init_zero:
        avgZero = avgZero/(init_zero-init_fi)
        print "Average zero crossing rate is "+str(avgZero)
        continue
    
    #
    # zero crossing check 
    #    
    if c > init_zero and c < init_zero+zero_term:
        if avg < val and zeroFlag is False:
            zero = zero + 1
            zeroFlag = True
        elif avg > val and zeroFlag is True:
            zero = zero + 1
            zeroFlag = False
        else:
            continue
    elif c == init_zero+zero_term:
        zero = zero/zero_term
        
        ser.write("s")
        time.sleep(0.01)
        ok = ser.readline()
        print zero, ok
        cPrs = 0.0
        for h in ok.split(','):
            cPrs = cPrs + int(h)
            
        if zero < avgZero*(1.0/2.0) and state is False and cPrs > 3*prs+1:
            state = True
            print "State is Working: ", ok

        if  zero - preZero > 0 and state is True:
            vibState = True
        
        # if environment noise is changed, than re-initializing
        if vibLoop > 10:
            c = 0
            vibLoop = 0
        if vibState is True:
            diff = avgZero - zero
            print "Foot Vibration: ", str(diff)
            ser.write("2")
            if diff < avgZero/2.0:
                time.sleep(0.01)
                ser.write("3")
            if diff < avgZero/3.0:
                time.sleep(0.01)
                ser.write("4")
            if diff < avgZero/4.0:
                time.sleep(0.01)
                ser.write("1")
                
            if vibLoopState is True:
                vibLoop = vibLoop + 1
            else:
                vibLoop = 0
        if avgZero < zero+0.05 and vibState is True:
            state = False 
            vibState = False
            print "State is Not Working"
        c = init_zero+1
        preZero = zero
        zero = 0.0
        vibLoopState = vibState
        
      
print "* done"
stream.stop_stream()
stream.close()
p.terminate()
